package com.katsu.myapplib.util;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;

public final class UtilInstance {
    private UtilInstance() {}

    public static <T> T Instance(Class<T> c) throws Exception {

        return (T) c.newInstance();

    }

    /**
     * 跟剧Class地址穿件类对象，并通过当前构造的类的构造方传参
     * @param c
     * @param constructors
     * @param objects
     * @param <T>
     * @return
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static <T> T Instance(Class<T> c, Class[] constructors, Object[] objects){

        try {

            Constructor ct = c.getDeclaredConstructor(constructors);

            ct.setAccessible(true);

            return (T) ct.newInstance(objects);

        } catch (NoSuchMethodException e) {

            e.printStackTrace();

        } catch (InstantiationException e) {

            e.printStackTrace();

        } catch (IllegalAccessException e) {

            e.printStackTrace();

        } catch (IllegalArgumentException e) {

            e.printStackTrace();

        } catch (InvocationTargetException e) {

            e.printStackTrace();

        }

        return null;

    }

    @SuppressWarnings("unchecked")
    public static <T> T InstanceGenericity(Class<?> c, int i) {

        try {

            return (T) Instance(GenericityClass(c, i));

        } catch (Exception e) {

            return null;

        }

    }

    public static Class<?> GenericityClass(Class<?> c, int i) {

        return (Class<?>) ((ParameterizedType) c.getGenericSuperclass()).getActualTypeArguments()[i];

    }

    public static boolean classExist(String s) {

        try {

            Class.forName(s);

            return true;

        } catch (Exception var2) {

            return false;

        }
    }
}
